package 算法.leetcode.offer;

/**
 * @author lchenglong
 * @date 2022/3/19
 */
public class Offer53 {

    public static void main(String[] args) {
        Offer53 instance = new Offer53();
        int[] arr = new int[]{1,2,6,6,7,7};
        int target = 7;
        int res = instance.search(arr, target);
        System.out.println(res);
    }
    public int search(int[] nums, int target) {
        //边界条件
        if (nums == null||nums.length ==0) return 0;
        // 二分查找
        int mid = nums.length/2,low = 0,high = nums.length-1;
        while (low<high){
            if (nums[mid] == target){
                break;
            } else if (nums[mid]<target){
                low = mid+1;
                mid = (high+low)/2;
            } else {
                high = mid-1;
                mid = (high+ low)/2;
            }
        }
        int count = 0;
        for (int i = mid;i<nums.length;i++){
            if (nums[i] == target)count++;
            else break;
        }
        for (int j= mid -1;j>=0;j--){
            if (nums[j] == target)count++;
            else break;
        }
        return count;
    }
}
